<?php

namespace app\admin\command;

use app\admin\model\BillModel;
use app\admin\model\BuildingRoomModel;
use app\admin\model\ContractFixedModel;
use app\common\model\PaymentRecords;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Contract extends Command
{

    protected function configure()
    {
        $this
            ->setName('deal_contract')
            ->setDescription('更新合同，生成账单');
    }

    protected function execute(Input $input, Output $output)
    {

        try {

            // 更新合同过期
            $list = \app\common\model\Contract::where([
                'end_time' => ['<', date('Y-m-d')],
                'status' => 1
            ])->select();
            foreach ($list as $item) {
                $id = $item->id;
                $item->status = 2;
                BuildingRoomModel::update([
                    'status' => 0,
                ], [
                    'room_id' => $item->room_id
                ]);

                // 更新合同状态
                $item->save();
            }


            //生成合同账单
            \app\common\model\Contract::where(['status' => 1])
                ->chunk(100, function ($rows) {
                    foreach ($rows as $row) {
                        if ($row->rent_day < 1) {
                            continue;
                        }
                        $rent_ymd = date('Y-m-' . $row->rent_day);
                        $rent_date = date('Y-m-d', strtotime('-' . $row->ahead_day . ' day', strtotime($rent_ymd)));
                        if ($rent_date != date('Y-m-d')) {
                            continue;
                        }

                        $contract_id = $row->id;
                        // 租金
                        $money = $row->money_zu;
                        // 固定费用 随房租付
                        $fixed_money = ContractFixedModel::where('contract_id', $contract_id)
                            ->whereNotIn('cfg_id', [1,2,3])
                            ->sum('price');

                        $money = bcadd($money, $fixed_money, 2);
                        // 水电
                        /*$water_e_money = RoomBoardLogModel::where([
                            'room_id' => $row->room_id,
                            'type' => ['in', [1, 2]],
                            'month' => date('Y-m'),
                        ])->sum('money');
                        $money = bcadd($money, $water_e_money, 2);*/


                        $other_data = [];
                        $fixed_list = ContractFixedModel::where('contract_id', $contract_id)
                            ->whereNotIn('cfg_id', [1,2,3])
                            ->select();
                        foreach ($fixed_list as $v) {
                            $other_data[] = [
                                'name' => $v['type_name'] ?? '',
                                'money' => $v['price'] ?? 0,
                            ];
                        }

                        $bill = BillModel::create([
                            'user_id' => $row->homeowner_id,
                            'contract_id' => $contract_id,
                            'status' => 0,
                            'money' => $money,
                            'year' => date('Y'),
                            'month' => date('Y-m'),
                            'day' => date('Y-m-d'),
                            'category' => '租金',
                            'type' => 1,
                            'remark' => '租金',
                            'other_data' => json_encode($other_data,JSON_UNESCAPED_UNICODE),
                        ], true);



                        PaymentRecords::create([
                            'homeowner_id' => $row->homeowner_id,
                            'contract_id' => $row->id,
                            'relation_id' => $bill->id,
                            'user_id' => $row->user_id,
                            'type' => PaymentRecords::TYPE_FANG,
                            'status' => PaymentRecords::STATUS_DEFAULT,
                            'money' => $money,
                            'other_data' => $other_data ? json_encode($other_data, JSON_UNESCAPED_UNICODE) : null,
                        ], true);

                    }
                });
            $output->writeln('合同处理成功');
        } catch (\Exception $e) {
            trace('合同处理异常：' . $e->getTraceAsString(), 'error');
            $output->writeln('合同处理失败' . $e->getMessage());
        }


    }


}
